package mh.demo.ehcache;

import mh.demo.PrintUtils;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class EhcacheDemojsr01 {

    public static void main(String[] args) throws URISyntaxException {
        CachingProvider provider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
        URL myUrl = EhcacheDemojsr01.class.getClassLoader().getResource("ehcache-demo-jsr-01.xml");

        CacheManager cacheManager = provider.getCacheManager(myUrl.toURI(), EhcacheDemojsr01.class.getClassLoader());
        Cache<String, List> cache = cacheManager.getCache("testList", String.class, List.class);
        PrintUtils.println("从磁盘中读到的缓存数据：");
        for (Cache.Entry<String, List> entry : cache) {
            PrintUtils.println("key=" + entry.getKey() + ", value=" + entry.getValue());
        }
        PrintUtils.println("重新缓存的数据：");
        Random random = new Random(System.currentTimeMillis());
        List<Integer> numbers = new ArrayList<>();
        List<Character> letters = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            numbers.add(random.nextInt(10));
            letters.add((char) random.nextInt(65, 91));
        }
        cache.put("number", numbers);
        cache.put("letter", letters);
        for (Cache.Entry<String, List> entry : cache) {
            PrintUtils.println("key=" + entry.getKey() + ", value=" + entry.getValue());
        }
        cacheManager.close();

    }
}
